//
//  PhotoShowViewController.m
//  item-NetEaseNews-tyw
//
//  Created by tyw on 15/10/2.
//  Copyright (c) 2015年 tyw. All rights reserved.
//

#import "PhotoShowViewController.h"
#import "PhotoShowCollectionView.h"
#import "NetEaseDataService.h"
#import "PhotoSetModel.h"
#import "PhotoModel.h"
#import "MBProgressHUD.h"

@interface PhotoShowViewController ()

@end

@implementation PhotoShowViewController {
    UIButton* backBtn;              //返回按钮
    
    UIButton* replyBtn;             //跟帖
    
    UILabel* titleLabel;            //新闻标题
    UILabel* contentLabel;          //新闻内容,tag = 1002
    UILabel* currentIndexLabel;     //当前照片的序号,tag = 1001
    UILabel* photoCountLabel;       //照片的总数
    
    PhotoShowCollectionView* _collectionView;       //照片们
    
    PhotoSetModel* photoSetModel;           //数据模型
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor blackColor];
    
    
    [self _createCollectionView];   //图片collectionView
    [self _createNavBar];       //顶部返回按钮和跟帖
    [self _createLabels];           //标题、新闻简介、图片当前序号、图片总数   四个label
    [self _createBottomBar];    //底部三个按钮
    
    [self _loadData];           //网络数据请求
    
    //接收图片被点击的通知，接收到后，控制一些UI的显隐
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(photoTapNotification) name:@"PhotoTapGestureNotification" object:nil];
}

- (void)photoTapNotification {
    [UIView animateWithDuration:0.3 animations:^{
        for (UIView* view in self.view.subviews) {
            if (![view isKindOfClass:[PhotoShowCollectionView class]]) {
                if (view.alpha != 1) {
                    view.alpha = 1;
                } else {
                    view.alpha = 0.01;
                }
            }
        }
        
        BOOL hidden = [[UIApplication sharedApplication] isStatusBarHidden];
        [[UIApplication sharedApplication] setStatusBarHidden:!hidden withAnimation:UIStatusBarAnimationFade];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)_loadData {
    //photoSetId  54GI0096|77938  这种样式   0096是代表页面类型（头条、NBA、娱乐、时尚）  77938应该对应相应的图集
    NSArray* array = [_photoSetId componentsSeparatedByString:@"|"];
    
    if (array.count == 2) {     //一定是2，否则这个skipId就不对
        NSString* Id = array[1];
        
        NSString* str = array[0];
        NSString* type = [str substringFromIndex:str.length-4];
        
        [NetEaseDataService photoShowDataRequestSkipId:Id type:type block:^(id result) {
            if ([result isKindOfClass:[NSError class]]) {
                NSLog(@"图集获取失败 %@", result);
                return;
            }
//            NSLog(@"%@", [Tools getJsonStrFromObj:result]);
            //刷新UI
            photoSetModel = [[PhotoSetModel alloc] initWithDataDic:result];
            titleLabel.text = photoSetModel.title;      //新闻标题
            photoCountLabel.text = [NSString stringWithFormat:@"/%li", [photoSetModel.imgCount integerValue]];
            
            //给collectionView赋值
            _collectionView.photoSetModel = photoSetModel;
        }];
    }
}

#pragma mark - 子视图们
- (void)_createNavBar {
    //返回按钮
    backBtn = [[UIButton alloc] initWithFrame:CGRectMake(5, 25, 44, 44)];
    [backBtn setImage:[UIImage imageNamed:@"imageset_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
    //跟帖
    replyBtn = [[UIButton alloc] initWithFrame:CGRectMake(kWidth-80, 30, 90, 40)];
    [replyBtn setBackgroundImage:[UIImage imageNamed:@"contentview_commentbacky"] forState:UIControlStateNormal];
    replyBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
    replyBtn.titleLabel.textColor = [UIColor whiteColor];
    replyBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    [replyBtn setTitle:@"1008跟帖" forState:UIControlStateNormal];
    [replyBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 25)];
    [self.view addSubview:replyBtn];
}

- (void)_createBottomBar {
    //底部view的最上面有一条小白线
    UIImageView* whiteLineImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, kHeight-50, kWidth, 0.25)];
    UIImage* line = [UIImage imageNamed:@"comment_ground_1"];
    [line stretchableImageWithLeftCapWidth:50 topCapHeight:1];
    whiteLineImgView.image = line;
//    whiteLineImgView.alpha = 0.6;
    [self.view addSubview:whiteLineImgView];
    
    //三个按钮,下载图片到本地、分享、收藏.....最后一个是收藏按钮的选中状态
    NSArray* btnNameArray = @[@"icon_download",@"icon_share_white",@"icon_star",@"icon_star_full"];
    for (int i = 0; i < 3; i++) {
        CGFloat width = 30;
        UIButton* btn = [[UIButton alloc] initWithFrame:CGRectMake(kWidth-10-(3-i)*(width+20)+10, kHeight-40, width, width)];
        [btn setImage:[UIImage imageNamed:btnNameArray[i]] forState:UIControlStateNormal];
        if (i == 2) {       //收藏按钮有两个状态
            [btn setImage:[UIImage imageNamed:btnNameArray[3]] forState:UIControlStateSelected];
        }
        [btn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = i+100;
        btn.backgroundColor = [UIColor clearColor];
        [self.view addSubview:btn];
    }
}

- (void)_createCollectionView {
    UICollectionViewFlowLayout* layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.itemSize = CGSizeMake(kWidth, kHeight-80);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;//滑动方向水平
    
    _collectionView = [[PhotoShowCollectionView alloc] initWithFrame:CGRectMake(0, 40, kWidth, kHeight-80) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_collectionView];
}

- (void)_createLabels {
    //新闻标题
    titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, kHeight-40-100, kWidth-60, 20)];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.font = [UIFont systemFontOfSize:16];
    titleLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:titleLabel];
    
    //新闻内容
    contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, kHeight-40-85, kWidth-20, 80)];
    contentLabel.textColor = [UIColor lightGrayColor];
    contentLabel.textAlignment = NSTextAlignmentLeft;
    contentLabel.font = [UIFont systemFontOfSize:12];
    contentLabel.numberOfLines = 4;
    contentLabel.tag = 1002;
    contentLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:contentLabel];
    
    //当前照片序号
    currentIndexLabel = [[UILabel alloc] initWithFrame:CGRectMake(kWidth-60, kHeight-40-100, 30, 20)];
    currentIndexLabel.textAlignment = NSTextAlignmentRight;
    currentIndexLabel.textColor = [UIColor whiteColor];
    currentIndexLabel.font = [UIFont systemFontOfSize:16];
    currentIndexLabel.backgroundColor = [UIColor clearColor];
    currentIndexLabel.tag = 1001;
    [self.view addSubview:currentIndexLabel];
    
    //照片总数
    photoCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(kWidth-30, kHeight-40-100+5, 30, 15)];
    photoCountLabel.textAlignment = NSTextAlignmentLeft;
    photoCountLabel.textColor = [UIColor whiteColor];
    photoCountLabel.font = [UIFont systemFontOfSize:12];
    photoCountLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:photoCountLabel];
}

#pragma mark - actions
- (void)backAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)buttonAction:(UIButton*)button {
    button.selected = !button.selected;
    
    if (button.tag == 100) {            //保存当前的图片
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"图片保存提示" message:@"保存当前图片到系统相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
        
    } else if (button.tag == 101) {     //分享
        
    } else {                            //收藏
        
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {     //取消
        NSLog(@"取消保存图片");
        
    } else if (buttonIndex == 1) {      //确定
        PhotoModel* model = photoSetModel.photoModelArray[_currentShowPhotoIndex];
        NSString* imgUrl = model.imgUrl;
        UIImage* image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]]];
        
        //显示菊花,提示保存
        MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
        hud.labelText = @"正在保存";
        [hud show:YES];
        hud.dimBackground = YES;
        
        //保存图片至相册
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)(hud));
    }
}

//相片保存完毕调用
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    MBProgressHUD* hud = (__bridge MBProgressHUD*)contextInfo;
    
    if (error) {        //保存失败
        hud.labelText = @"保存失败";
        hud.mode = MBProgressHUDModeText;
        [hud hide:YES afterDelay:1.5];
    } else {            //保存成功
        hud.labelText = @"保存成功";
        hud.mode = MBProgressHUDModeCustomView;
        UIImageView* customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark"]];
        hud.customView = customView;
        
        [hud hide:YES afterDelay:1.5];
    }
}

#pragma mark - dealloc
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"PhotoTapGestureNotification" object:nil];
}

@end
